/**
 *    https://gitee.com/gitsc/pro-cloud/
 *     @Author Aijm 2929793435@qq.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.cloud.auth.component;

import com.cloud.common.util.base.Result;
import com.cloud.common.util.enums.ResultEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;

import java.io.Serializable;


/**
 * 授权服务器 异常统一处理
 * @author Aijm
 * @since 2019/5/16
 */
@Slf4j
public class Auth2ResponseExceptionTranslator implements WebResponseExceptionTranslator {

    @Override
    public ResponseEntity translate(Exception e) {
        log.error("授权服务器 异常统一处理:异常:{}", e.getMessage(), e);
        if (e instanceof InvalidTokenException){
            Result<Serializable> error = Result.error(ResultEnum.TOKEN_PAST);
            return new ResponseEntity(error, HttpStatus.OK);
        } else if (e instanceof UsernameNotFoundException) {
            Result<Serializable> error = Result.error(ResultEnum.LOGIN_NAME);
            return new ResponseEntity(error, HttpStatus.OK);
        } else if (e instanceof InvalidGrantException) {
            Result<Serializable> error = Result.error(ResultEnum.LOGIN_PASSWORD);
            return new ResponseEntity(error, HttpStatus.OK);
        } else if (e instanceof BadCredentialsException) {
            Result<Serializable> error = Result.error(ResultEnum.ERROR);
            return new ResponseEntity(error, HttpStatus.OK);
        }
        return new ResponseEntity(Result.error(""), HttpStatus.OK);
    }
}